package com.longteng.diamond.service;

import com.longteng.diamond.dao.InterfaceMockMapper;
import com.longteng.diamond.dao.InterfaceScriptMapper;
import com.longteng.diamond.domain.InterfaceScript;
import com.longteng.diamond.domain.ReportLog;
import com.longteng.diamond.util.ReportLogFileUtil;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.FileWriter;
import java.io.IOException;

/**
 * Created by Administrator
 * DATE : 2018/8/12
 * TIME : 16:22
 * PROJECT : java-lesson
 * PACKAGE : com.longteng.lesson
 *
 * @author <a href="mailto:taki@qq.com">Administrator</a>
 */
@Component
public class ScriptService {

    @Autowired
    InterfaceScriptMapper interfaceScriptMapper;

    @Autowired
    InterfaceMockMapper interfaceMockMapper;
    /**
     * 修改脚本开启debug状态
     * @param interfaceScript
     * @return
     */
    public void updateDebugStatus(InterfaceScript interfaceScript){
        interfaceScriptMapper.updateDebugStatus(interfaceScript);
    }
    /**
     * 清空日志内容
     * @param fileName
     * @return
     */
    public void clearLog(String fileName){
        FileWriter fileWriter= null;
        try {
            fileWriter = new FileWriter(fileName+ ".log");
            IOUtils.write(" ",fileWriter);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                fileWriter.flush();
                fileWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
    /**
     * 获取script脚本
     * @param
     * @return
     */
    public InterfaceScript getScript(Integer interfaceMockId) {
        return interfaceScriptMapper.getInterfaceScript(interfaceMockId);
    }
    /**
     * 修改groovy脚本
     * @param
     * @return
     */
    public void updateScript(InterfaceScript interfaceScript) {
        if (null == interfaceScript.getId()) {
            interfaceScriptMapper.addScript(interfaceScript);
        } else {
            interfaceScriptMapper.updateScript(interfaceScript);
        }
    }
    /**
     * 读取日志,根据记录的最后一次大小读取文件
     * @param fileName
     * @param lastTimeFileSize
     * @return
     */
    public ReportLog debugLog(String fileName, Long lastTimeFileSize) {
        ReportLog reportLog=new ReportLog();
        if (null != lastTimeFileSize) {
            ReportLogFileUtil reportLogFileUtil = new ReportLogFileUtil();
            reportLog = reportLogFileUtil.read(fileName+".log",lastTimeFileSize);
        }
        return reportLog;
    }
}
